package com.zt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.api.UserInfoFeign;
import com.zt.service.TransactionRecordService;
import com.zt.service.WithdrawalService;
import com.zt.system.CardBinding;
import com.zt.service.CardBindingService;
import com.zt.mapper.CardBindingMapper;
import com.zt.system.TransactionRecord;
import com.zt.system.vo.CardTableVO;
import com.zt.user.UserInfo;
import com.zt.system.Withdrawal;
import com.zt.utils.Result;
import com.zt.vo.CardBindingVo;
import com.zt.system.CardBinding;
import com.zt.user.UserInfo;
import com.zt.utils.Result;
import com.zt.vo.Vo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import java.util.Random;

/**
* @author 不.凌
* @description 针对表【card_binding】的数据库操作Service实现
* @createDate 2024-09-03 17:42:54
*/
@Service
public class CardBindingServiceImpl extends ServiceImpl<CardBindingMapper, CardBinding>
    implements CardBindingService{

    private static final int DAILY_LIMIT = 10000; // 单日限额10000

    private static boolean isLimitExceeded = false; // 标记是否超出单日限额

    private static int withdrawalCount = 0;

    private static int money = 0; // 今日提现金额
    @Resource
    private CardBindingMapper cardBindingMapper;

    @Resource
    private TransactionRecordService transactionRecordService;
    @Resource
    private UserInfoFeign userInfoFeign;


    @Override
    public boolean savebingcard(CardBinding cardBinding) {

        Random random = new Random();
        StringBuilder cardNumber = new StringBuilder("6");
        for (int i = 1; i < 20; i++) {
            cardNumber.append(random.nextInt(10));
        }
        cardBinding.setCardNumber(String.valueOf(cardNumber));
        cardBinding.setUserId(1);
        int insert = cardBindingMapper.insert(cardBinding);
        return insert>0;
    }



    @Override
    public Result updatebangstatus(CardBinding cardBinding) {
        int i = cardBindingMapper.updateById(cardBinding);
        return Result.success(i);
    }

    @Override
    public Result code() {
        int i = new Random().nextInt(1000) + 9000;
        return Result.success(String.valueOf(i));
    }

    @Resource
    private WithdrawalService withdrawalService;

    @Override
    public Result getCardBindingById(Integer uid) {
        System.out.println(uid);
        List<CardBinding> list = this.list(Wrappers.<CardBinding>lambdaQuery().eq(CardBinding::getUserId, uid));
//        System.err.println("12312312"+list);

        return Result.success(list);
    }


    @Override
    public Result Recharge(CardBindingVo cardBindingVo) {
        //根据银行卡的卡号和密码查询
        CardBinding cardBinding = cardBindingMapper.getUserById(cardBindingVo);
        if(cardBinding==null){
            return Result.error("银行卡不存在");
        }
        if(cardBinding.getCardType()==3){
            return Result.error("该银行卡已被冻结，无法使用");
        }
        if(!cardBinding.getBankNumber().equals(cardBindingVo.getBankNumber())){
            return Result.error("银行卡密码错误");
        }
        //银行卡原本的余额
        Integer balance = cardBinding.getBalance();
        //拿到用户输入的金额
        Integer balance1 = cardBindingVo.getBalance();
        if(balance1==0){
            return Result.error("充值金额不能为零");
        }
        cardBinding.setBalance(balance+balance1);
        this.updateById(cardBinding);
        //拿到当前操作的用户
        Integer userId = cardBinding.getUserId();
        //添加交易记录
        TransactionRecord transactionRecord = new TransactionRecord();
        transactionRecord.setAmount(BigDecimal.valueOf(balance1));
        transactionRecord.setBindingId(cardBinding.getBindingId());
        transactionRecord.setTransactionDate(new Date());
        transactionRecord.setTransactionType(0);
        transactionRecord.setUserId(userId);
        transactionRecordService.save(transactionRecord);
        return Result.success("充值成功");
    }

    @Override
    public String getCardNumber(Integer bindingId) {
        CardBinding cardBinding = this.getOne(Wrappers.<CardBinding>lambdaQuery().eq(CardBinding::getBindingId, bindingId));
        String cardNumber = cardBinding.getCardNumber();
        return cardNumber;
    }

    @Override
    public CardBinding CardBindingByCardNumber(String cardNumber) {
        CardBinding cardBinding = this.getOne(Wrappers.<CardBinding>lambdaQuery().eq(cardNumber!=null,CardBinding::getCardNumber, cardNumber));
        return cardBinding;
    }
    @Override
    public CardBinding cardBindingByUserId() {
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        CardBinding one = this.getOne(Wrappers.<CardBinding>lambdaQuery()
                .eq(userInfoUserId.getUserId() != null, CardBinding::getUserId, userInfoUserId.getUserId())
                .eq(CardBinding::getCardType, 0));
        return one;
    }

    @Override
    public CardBinding cardBindingByCardNumber(String cardNumber) {
        CardBinding one = this.getOne(Wrappers.<CardBinding>lambdaQuery()
                .eq(cardNumber != null, CardBinding::getCardNumber, cardNumber));
        return one;
    }

    @Override
    public Result cardBindingByBindingIdUpdate(CardTableVO cardTableVO) {
        System.err.println(cardTableVO);
        CardBinding one = this.getOne(Wrappers.<CardBinding>lambdaQuery()
                .eq(cardTableVO.getCardNumber() != null, CardBinding::getCardNumber, cardTableVO.getCardNumber()));
        BigDecimal subtract = cardTableVO.getMount().subtract(cardTableVO.getTotalMount());
        BigDecimal totalMount = BigDecimal.valueOf(one.getBalance());
        BigDecimal add = subtract.add(totalMount);
        Integer add1 = add.intValue();
        one.setBalance(add1);
        boolean save = this.updateById(one);
        return Result.success("成功");
    }

    @Override
    public List<CardBinding> cardBindingFindByUserId() {
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        List<CardBinding> list = this.list(Wrappers.<CardBinding>lambdaQuery()
                .eq(userInfoUserId.getUserId() != null, CardBinding::getUserId, userInfoUserId.getUserId()));
        return list;
    }

    @Override
    public Result cardBindingPayBackByBindingId(CardTableVO cardTableVO) {
        System.out.println(cardTableVO);
        CardBinding one = this.getOne(Wrappers.<CardBinding>lambdaQuery()
                .eq(cardTableVO.getCardNumber() != null, CardBinding::getCardNumber, cardTableVO.getCardNumber()));
        int i = cardTableVO.getMount().intValue();
        int i1 = one.getBalance() - i;
        one.setBalance(i1);
        boolean b = this.updateById(one);
        return b?Result.success("成功"):Result.error("失败");
    }


    @Override
    @Transactional
    public Result withdrawal(CardBindingVo cardBindingVo) {
        // 付款账户
        CardBinding cardBinding = this.getOne(Wrappers.<CardBinding>lambdaQuery().eq(CardBinding::getCardNumber, cardBindingVo.getCardNumber()));
        if (cardBinding == null) {
            return Result.error("付款账户不存在");
        }
        // 收款账户
        CardBinding cardBinding1 = this.getOne(Wrappers.<CardBinding>lambdaQuery().eq(CardBinding::getCardNumber, cardBindingVo.getSardNumber()));
        if (cardBinding1 == null) {
            return Result.error("收款账户不存在");
        }
        if (cardBindingVo.getCardNumber().equals(cardBindingVo.getSardNumber())) {
            return Result.error("不能转账给自己");
        }
        if (cardBindingVo.getBalance() == 0) {
            return Result.error("转账金额不能为零");
        }
        if (cardBindingVo.getBalance() > cardBinding.getBalance()) {
            return Result.error("当前余额不足，无法转账");
        }
        if (withdrawalCount <= 3) {
            // 收款
            if (cardBinding1.getCardType()!= 3) {
                cardBinding1.setBalance(cardBinding1.getBalance() + cardBindingVo.getBalance());
                this.updateById(cardBinding1);
            } else {
                return Result.error("收款银行卡已被冻结，无法使用");
            }
            // 付款
            if (cardBinding.getBankNumber().equals(cardBindingVo.getBankNumber())) {
                if (cardBinding.getCardType()!= 3) {
                    if (!isLimitExceeded && cardBinding1.getBalance() <= DAILY_LIMIT) {
                        // 超过一万后限额
                        if (money < 10000) {
                            // 用户提现金额叠加
                            money += cardBindingVo.getBalance();
                            cardBinding.setBalance(cardBinding.getBalance() - cardBindingVo.getBalance());
                            // 减去提现金额
                            this.updateById(cardBinding);
                        }
                    } else {
                        return Result.error("交易失败今天已超过单日限额！");
                    }
                } else {
                    return Result.error("付款银行卡已被冻结，无法使用");
                }
            } else {
                return Result.error("银行卡密码错误");
            }
        }else {
            return Result.error("今日提现次数已达上限，无法继续提现");
        }
        withdrawalCount++;
        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setAmount(BigDecimal.valueOf(cardBindingVo.getBalance()));
        withdrawal.setUserId(cardBinding.getUserId());
        withdrawal.setWithdrawalDate(new Date());
        withdrawalService.save(withdrawal);
        return Result.success("提现成功");
    }
}